<?php

namespace App\Models\video;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use Illuminate\Database\Eloquent\Model;

// 用户表
class VideoUserModel extends Model
{
    protected $table = "up_user"; //表名
    const CREATED_AT = null;
    const UPDATED_AT = null;

    public static function transferField($data){
        if(!$data){
            return [];
        }
        $data = UpTools::transferFields($data);
        if(isset($data[0])){
            foreach ($data as $k => $item){
                if(!empty($item["registerTime"])){
                    $data[$k]["registerTime"] = date("Y-m-d H:i", $item["registerTime"]);
                }
                if(!empty($item["updateTime"])){
                    $data[$k]["updateTime"] = date("Y-m-d H:i", $item["updateTime"]);
                }
                if(!empty($item["levelTime"])){
                    $data[$k]["levelTime"] = date("Y-m-d", $item["levelTime"]);
                }
            }
        }else{
            if(!empty($data["registerTime"])){
                $data["registerTime"] = date("Y-m-d H:i", $data["registerTime"]);
            }
            if(!empty($data["updateTime"])){
                $data["updateTime"] = date("Y-m-d H:i", $data["updateTime"]);
            }
            if(!empty($data["levelTime"])){
                $data["levelTime"] = date("Y-m-d", $data["levelTime"]);
            }
        }
        return $data;
    }

    //分页获取所有字段数据
    public static function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "create_time", $sort = "desc"){
        $db = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field));
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$limit);
        $data['list'] = $db->skip(($page - 1) * $limit)->take($limit)->orderBy($order, $sort)->get();
        if($data['list']){
            $data['list'] = self::transferField($data['list']->toArray());
        }
        return $data;
    }

    //根据条件获取数量
    public static function getCount($filter){
        if(!empty($filter)){
            return self::query()->where($filter)->count();
        }else{
            return self::query()->count();
        }
    }

    //添加
    public static function add($data, $getId=false){
        if(!$data)
            return true;
        try {
            $data["mall_id"] = request()->mallData["id"];
            //判断手机号是否重复
            if(!empty($data["mobile"])){
                if(!preg_match('/^1[3456789]\d{9}$/', $data["mobile"])){
                    return ErrorCode::code("customized", "手机号错误");
                }
                if(self::getCount(["mobile" => $data["mobile"], "mall_id" => $data["mall_id"]])){
                    return ErrorCode::code("mobile_exist");
                }
            }
            if(empty($data["update_time"])) $data["update_time"] = time();
            if ($getId) {
                $id = self::query()->insertGetId($data);
                return $id;
            } else {
                return self::query()->insert($data);
            }
        }catch (\Exception $e){
            return ErrorCode::code("customized", $e->getMessage());
        }
    }

    //更新
    public static function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        //判断手机号是否重复
        if(!empty($data["mobile"])){
            if(!preg_match('/^1[3456789]\d{9}$/', $data["mobile"])){
                return ErrorCode::code("customized", "手机号错误");
            }
            if(self::getCount([["mobile", '=', $data["mobile"]], ["id", '<>', $filter["id"]], ["mall_id", "=", request()->mallData["id"]]])){
                return ErrorCode::code("mobile_exist");
            }
        }
        if(empty($data["update_time"])) $data["update_time"] = time();
        $res = self::query()->where($filter)->update($data);
        if($res || $res === 0){
            return true;
        }else{
            return false;
        }
    }

    //获取某字段的值
    public static function getValue($field, $filter = []){
        if(!is_array($field)){
            return self::query()->where($filter)->value($field);
        }
        return false;
    }

    //获取多字段数据
    public static function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field))->first();
            return $data ? ($toArray ? self::transferField($data->toArray()) : UpTools::transferFields($data->toArray())) : [];
        }else{
            $data = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field))->get()->toArray();
            return $data ? ($toArray ? self::transferField($data) : UpTools::transferFields($data)) : [];
        }
    }
}